package com.newtouch.cq.base.starter.business.model.vo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.newtouch.cq.base.starter.business.entity.SysMenu;
import com.newtouch.cq.base.starter.business.entity.SysUser;
import com.newtouch.cq.base.starter.lang.em.MenuTypeEnum;
import com.newtouch.cq.base.starter.lang.util.TreeUtilParentAble;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 用户权限模型
 * @author Alex
 */
@Data
@JsonInclude(Include.NON_NULL)
@ApiModel("用户权限模型")
public class UserPermissionInfoModel implements Serializable {
	private static final long serialVersionUID = -4977567181160631848L;

	//SysRoleVo
	public UserPermissionInfoModel(SysUser user, List<? extends SysMenu> menuList, List<Object> roleList) {
		this.userName = user.getUsername();
		this.headImage = user.getHeadImage();
		this.isAdmin = user.getId() == 1;
		this.userRoles = CollUtil.newArrayList();
//		if(CollectionUtil.isNotEmpty(roleList)) {
//			roleList.stream().filter(role -> StrUtil.isNotBlank(role.getRoleCode())).forEach(role -> {
//				userRoles.add(role.getRoleCode());
//			});
//		}
        accessMenus = CollUtil.newArrayList();
        accessRoutes = CollUtil.newArrayList();
		userPermissions = new ArrayList<>(menuList.size());
        List<RouteTreeModel> accessRoutesChildren = new ArrayList<>();
		menuList.sort(Comparator.comparing(e -> e.getSort()));
		menuList.stream().forEach(menu -> {
			if(StrUtil.isNotEmpty(menu.getPermission())) {
				userPermissions.add(menu.getPermission());
			}
			if(ObjectUtil.isNotNull(menu.getType()) && menu.getType() == MenuTypeEnum.MENU) {
				MenuTreeModel pm = new MenuTreeModel(menu);
				accessMenus.add(pm);
				if(!StrUtil.equalsIgnoreCase(menu.getComponent(), "Layout")) {
					RouteTreeModel route = new RouteTreeModel(menu);
					accessRoutesChildren.add(route);
				}
			}
		});
		accessMenus = TreeUtilParentAble.buildTree(accessMenus);
		RouteTreeModel top = new RouteTreeModel();
		top.setName("index");
		top.setPath("/");
		top.setChildren(accessRoutesChildren);
		accessRoutes.add(top);
	}

	@ApiModelProperty("用户名称")
	protected String userName;
	@ApiModelProperty("用户头像")
	protected String headImage;
	@ApiModelProperty("是否admin")
	protected boolean isAdmin;
	@ApiModelProperty("用户权限")
	protected List<String> userPermissions;
	@ApiModelProperty("用户角色")
	protected List<String> userRoles;
	@ApiModelProperty("用户菜单树")
	protected List<MenuTreeModel> accessMenus;
	@ApiModelProperty("用户路由树")
	protected List<RouteTreeModel> accessRoutes;

}
